<template>
  <div class="content" style="background: pink">
    <u-popup v-model="goodsDetailShowFlag" mode="bottom" border-radius="14" :safe-area-inset-bottom="true" :closeable="true" close-icon-pos="top-left" close-icon="arrow-left" close-icon-color="#3B3B3B" :close-icon-size="36" z-index="99999">
      <view class="goosDetailshow-box" :style="{ height: `calc(100vh - ${tabBarHeight}px)` }">
        <view class="popup_top">
          <!-- 用来显示左上角关闭按钮，占位盒子，无作用 -->
        </view>
        <view class="detailImg-box flex-row-plus">
          <image class="detailImg" :src="selectedSku.image"></image>
          <view class="flex-column-plus mar-left-40 fs36" style="flex: 1; overflow: hidden">
            <view class="u-line-1 fs28" style="margin-bottom: 10rpx">{{ productData.productName || "" }}</view>

            <view class="flex items-center" style="height: 56rpx; margin-bottom: 10rpx">
              <view style="color: #ff5000"> ¥ {{ selectedSku.price }} </view>
              <view style="text-decoration: line-through; color: #9f9f9f" class="fs24 mar-left-20"> ¥ {{ selectedSku.originalPrice }} </view>
            </view>

            <view class="goodsNumCent">
              <view class="goodsNum-box flex-row-plus flex-sp-between items-center" :class="{ 'bottom-line': aliAgingObj.supportHanaUta }">
                <view class="goodsNum">
                  <view class="item subtract" :style="{ color: buyNum == 1 ? '#9F9F9F' : '#000000' }" @click="handleNumSub">-</view>
                  <view class="item goodsNumber">{{ buyNum }} </view>
                  <view class="item add" :style="{ color: buyNum == selectedSku.stockNumber ? '#9F9F9F' : '#000000' }" @click="handleNumAdd">+</view>
                </view>
                <label class="fs24 font-color-999 mar-left-20">库存 {{ selectedSku.stockNumber }} 件</label>
              </view>
            </view>
          </view>
        </view>
        <view class="color-box flex-column-plus">
          <view v-for="(skuRowItem, skuRowIndex) in productData.names" :key="skuRowIndex">
            <label class="fs26 font-color-333" v-if="skuRowItem['nameCode']">{{ skuRowItem.skuName }}：</label>
            <view class="colorName-box">
              <view class="pad-bot-30" v-for="(skuColItem, skuColIndex) in skuRowItem.values" :key="skuColIndex">
                <view class="colorName" :class="{ 'colorName-on': selectedAttr[skuRowItem['nameCode']] === skuColItem.valueCode }" @click="handleClickSkuItem(skuRowItem['nameCode'], skuColItem.valueCode)">
                  {{ skuColItem.skuValue? skuColItem.skuValue : '默认规格' }}
                </view>
              </view>
            </view>
          </view>
        </view>

        <view v-if="btnType === 6" class="skuSelectBtn undercarriage">
          <view class="flex-row-plus offShelf" v-if="productData.shelveState === 0"> 商品已下架 </view>
          <view class="flex-row-plus flex-items flex-sp-around" v-else>
            <view class="selectJoinShop selectBtn" @click="handleAddCart">加入购物车 </view>
            <view class="selectBuyNow selectBtn" @click="handleBuyNow">立即购买 </view>
          </view>
        </view>
        <view v-else>
          <view class="goosDetailbut-box flex-row-plus" :style="{ 'padding-bottom': (isIphone === true ? 60 : 20) + 'rpx' }">
            <view class="btn" v-if="btnType === 1" @click="handleAddCart">确认</view>
            <view class="btn" v-else @click="handleBuyNow(2)">确认</view>
          </view>
        </view>
      </view>
    </u-popup>
    <u-toast ref="uToastRef" zIndex="999999" />
  </div>
</template>

<script setup>
// 是否展示SKU弹窗
import { inject, onMounted, ref, toRefs, computed } from "vue";
import { request } from "@/utils/request";
import API from "@/config/api";
import { btnUseLoading } from "@/hooks/bntUseLoading";
import { useStore } from "vuex";

const store = useStore();
const tabBarHeight = computed(() => store.state.globalSetting.appSetting.tabBarHeight);

const { btnShowLoading } = btnUseLoading();
const emit = defineEmits(["getCurrentSku", "postSelectSku", "getInitSku"]);
const $store = inject("$store");
const goodsDetailShowFlag = ref(false);
// 已经选中的valueCode key => value  names.nameCode=>values.valueCode 处理选中渲染
const selectedAttr = ref({});
// 当前选中的skuMap对象（服务端数据）
const selectedSku = ref({});
const shopDiscountId = ref(0);
const shopSeckillId = ref(0);
// 1加入购物车 2立即购买 3开团 4单独购买 6SKU选择
const btnType = ref(0);
const buyNum = ref(1);
const uToastRef = ref()
// 花呗对象
const aliAgingObj = ref({
  supportHanaUta: false,
  selectIndex: -1,
  disableSelectList: [true, true, true],
  agingMoneyList: ["0.00", "0.00", "0.00"],
});

const props = defineProps({
  productData: {
    type: Object,
    default: () => ({}),
  },
  isIphone: {
    type: Boolean,
    default: () => false,
  }
});
const { productData, isIphone } = toRefs(props);
// 获取默认sku
onMounted(() => {
  emit("getInitSku");

  console.log("productData==", productData.value);
});

/**
 * 当前SKU数量减少
 */
function handleNumSub() {
  if (buyNum.value > 1) {
    buyNum.value = buyNum.value - 1;
  } else {
    uToastRef.value.show({
      title: '亲！至少一件哦！',
    })
  }
}

/**
 * 当前SKU数量加
 */
function handleNumAdd() {
  if (buyNum.value < selectedSku.value.stockNumber) {
    buyNum.value = buyNum.value + 1;
  } else {
    uToastRef.value.show({
      title: '库存不足',
    })
  }
}

/**
 * 根据skuId选择SKU
 * @param skuId SkuId
 */
function handleSelectBySkuId(skuId) {
  if (!skuId) return;
  // 当前商品后端返回的所有sku的排列组合
  const allSkuValueGroupMap = productData.value.map;
  for (const allSkuValueGroupMapKey in allSkuValueGroupMap) {
    if (parseInt(allSkuValueGroupMap[allSkuValueGroupMapKey].skuId) !== parseInt(skuId)) continue;
    selectedSku.value = allSkuValueGroupMap[allSkuValueGroupMapKey];
    echoFatherRowText(productData.value, selectedSku.value, buyNum.value);
    // 控制组件选中渲染
    const selectValueCodes = (selectedSku.value["valueCodes"] || "").split(",");
    for (const skuRow of productData.value.names) {
      for (const skuCol of skuRow.values) {
        if (!selectValueCodes.includes(skuCol["valueCode"])) continue;
        selectedAttr.value[skuRow["nameCode"]] = skuCol["valueCode"];
        break; // 一行的sku只会有一个value
      }
    }
  }
}

/**
 * 点击sku的一项
 * @param nameCode SKU行的nameCode
 * @param valueCode SKU列的valueCode
 * nameCodeValueCodeClick
 */
function handleClickSkuItem(nameCode, valueCode) {
  // 当前选中
  selectedAttr.value[nameCode] = valueCode;
  // 获取到所有的sku的values.valueCode
  let values = [];
  for (const key in selectedAttr.value) {
    values.push(selectedAttr.value[key]);
  }
  // 当前选中的sku的key组合
  // 后端返回的productData.map中，排列组合了所有values[].valueCode的情况，使用逗号分隔
  const nowSelectSkuValueGroupKey = values.join(","); // 相较于allSkuValueGroupMap的key
  // 后端返回的所有sku组合（values.valueCode）
  const allSkuValueGroupMap = productData.value.map;
  // 遍历后端数据
  for (const allSkuValueGroupMapKey in allSkuValueGroupMap) {
    // 当和当前选中的sku一致
    if (nowSelectSkuValueGroupKey === allSkuValueGroupMapKey) {
      selectedSku.value = allSkuValueGroupMap[allSkuValueGroupMapKey];
      echoFatherRowText(productData.value, selectedSku.value, buyNum.value);
    }
  }
}

/**
 * 回显父组件（通讯）
 * @param productData 当前商品对象
 * @param skuItem 当前选中的sku的后端数据
 * @param buyNum 当前sku购买数量
 */
function echoFatherRowText(productData, skuItem, buyNum) {
  // 获取到当前选中的sku的valueCode
  const currentSku = [];
  // 取出所有的valueCode
  const nowSelectValueCodeList = (skuItem["valueCodes"] || "").split(",");
  const skuRows = productData.names;
  for (const skuRow of skuRows) {
    const skuValues = skuRow.values;
    for (const skuValue of skuValues) {
      if (!nowSelectValueCodeList.includes(skuValue.valueCode)) continue;
      const currentSkuItem = { skuText: "" };
      if (skuValue.valueCode === "单款项") {
        currentSkuItem["skuText"] = skuValue["skuValue"];
      } else {
        currentSkuItem["skuText"] = `${skuValue.skuName}:${skuValue.skuValue}`;
      }
      currentSku.push(currentSkuItem);
      break; // 只会对应一个value数据，找到就break减少循环
    }
  }
  emit("getCurrentSku", {
    skuItem,
    currentSku,
    buyNum,
  });
  // 选中sku之后，做一些相应的操作
  // postSelectSku依赖于getCurrentSku的数据
  emit("postSelectSku");
}

//加入购物车
async function handleAddCart() {
  btnShowLoading();
  handleCheckIsLogin();
  if (selectedSku.value.stockNumber < 1) {
    uToastRef.value.show({
      title: '库存不足',
    })
    return false
  }
  // uni.showLoading({
  //   mask: true,
  //   title: '添加中...',
  // })
  try {
    const postData = {
      skuId: selectedSku.value.skuId,
      number: buyNum.value,
    };
    await request(API.ShoppingaddCart, postData, "POST");
    // 埋点
    $store.dispatch("doPointer", {
      eventType: 2,
      productIds: productData.value.productId,
    });
    // 给购物车小图标赋值数量
    let newAllCartNum = uni.getStorageSync("allCartNum") + buyNum.value;
    uni.setStorageSync("allCartNum", newAllCartNum);
    emit("changeCartNum", newAllCartNum);
    buyNum.value = 1;
    goodsDetailShowFlag.value = false;
    setTimeout(() => {
      uToastRef.value.show({
        title: '添加成功',
      })
    }, 500);
  } finally {
    // uni.hideLoading()
  }
}

/**
 * 立即购买（下单）
 */
function handleBuyNow() {
  handleCheckIsLogin();
  if (selectedSku.value.stockNumber < 1) {
    uToastRef.value.show({
      title: '库存不足',
    })
    return false
  }
  if (buyNum.value > selectedSku.value.stockNumber && selectedSku.value.stockNumber !== 0) {
    uToastRef.value.show({
      title: '已超出最大数量限制',
    })
    return false
  }

  //组装后端数据
  let list = [
    {
      ifWork: 0,
      shopId: productData.value.shopId,
      shopName: productData.value.shopName,
      shopDiscountId: shopDiscountId.value > 0 ? shopDiscountId.value : null,
      shopSeckillId: shopSeckillId.value > 0 ? shopSeckillId.value : null,
      skus: [
        {
          productId: productData.value.productId,
          skuId: selectedSku.value.skuId,
          productName: productData.value.productName,
          image: selectedSku.value.image,
          price: selectedSku.value.price,
          weight: 0,
          number: buyNum.value,
          SKU: "",
          total: selectedSku.value.price * buyNum.value,
          ifLogistics: 1,
        },
      ],
    },
  ];
  uni.setStorageSync("skuItemDTOList", list);
  buyNum.value = 1;
  goodsDetailShowFlag.value = false;
  uni.navigateTo({
    url: "../orderModule/orderConfirm?type=1",
  });
}

/**
 * 是否登录
 * @return {boolean|void}
 */
function handleCheckIsLogin() {
  const userInfo = uni.getStorageSync("storage_key");
  if (!userInfo || (userInfo && JSON.stringify(userInfo) === "{}")) {
    return uni.navigateTo({
      url: "/zwx_category_page2/userModule/login",
    });
  }
  return true;
}

defineExpose({ handleSelectBySkuId, btnType, goodsDetailShowFlag });
</script>

<style lang="scss" scoped>
.goosDetailshow-box {
  // margin-bottom: -5upx;
  .popup_top {
    height: 100rpx;
    background: #f2f6f9;
  }

  .detailImg-box {
    margin-top: 30upx;
    margin-left: 30upx;
    border-bottom: 1upx solid #ededed;
    padding-bottom: 20upx;
    width: 690upx;

    .detailImg {
      width: 180upx;
      height: 180upx;
    }
  }

  .color-box {
    padding: 30upx 30upx 100upx;
    // width: 690upx;

    .colorName-box {
      display: flex;
      flex-wrap: wrap;
      flex-direction: row;
      justify-content: flex-start;
      align-items: center;
      margin-top: 30upx;
      // margin-left: -30upx;

      .colorName {
        // width: 104rpx;
        padding: 10rpx 24rpx;
        background: #f2f6f9;
        border-radius: 8rpx 8rpx 8rpx 8rpx;
        line-height: 36rpx;
        color: #3d3d3d;
        font-size: 28rpx;
        margin-right: 20rpx;
      }

      .colorName-on {
        background: #ff5000;
        color: #fff;
      }
    }
  }

  .modelNum-box {
    padding: 30upx 30upx;
    border-bottom: 1upx solid #ededed;
    width: 690upx;

    .modelNumName-box {
      display: flex;
      flex-wrap: wrap;
      flex-direction: row;
      justify-content: flex-start;
      align-items: center;
      margin-top: 30upx;
      margin-left: -30upx;

      .modelNumName-on {
        background-color: #ffe4d0;
        color: #ff7800;
        margin-left: 30upx;
        padding: 10upx 32upx;
        border-radius: 28upx;
        border: 1upx solid #ff7800;
        font-size: 26upx;
        text-align: center;
      }

      .modelNumName {
        background-color: #f5f5f5;
        margin-left: 30upx;
        padding: 10upx 32upx;
        border-radius: 28upx;
        font-size: 26upx;
      }
    }
  }

  .goodsNumCent {
    .goodsNum-box {
      width: 100%;
      // padding: 30rpx 0 180rpx 0;
      // border-top: 2rpx solid #ededed;
      .goodsNum {
        height: 50upx;
        display: flex;
        align-items: center;

        .item {
          height: 48rpx;
          border: 1rpx solid #cccccc;
          box-sizing: border-box;
          text-align: center;
        }

        .subtract {
          border-right: 0upx;
          border-radius: 50upx 0 0 50upx;
          width: 70rpx;
          line-height: 1.2;
        }

        .goodsNumber {
          width: 64rpx;
          font-size: 28rpx;
          line-height: 1.5rem;
        }

        .add {
          border-left: 0upx;
          border-radius: 0 50upx 50upx 0;
          width: 70rpx;
          line-height: 1.2;
        }
      }
    }
  }

  .bottom-line {
    border-bottom: 1upx solid #ededed;
  }

  .huabei-box {
    padding: 30upx 30upx;
    width: 690upx;

    .fenqi-box {
      margin-top: 15upx;
      width: 120%;

      .huabei-item {
        display: inline-block;
        background: #f3f3f3;
        padding: 16upx 24upx;
        margin: 5upx 10upx;
        border-radius: 15upx;
        text-align: center;
        font-size: 7upx;

        .huabei-period {
          display: block;
        }
      }

      .fenqi-on {
        border: 1px solid #ef7f93;
        color: #ef7f93;
      }

      .disabled {
        color: #cacaca;
      }
    }
  }

  .goosDetailbut-box {
    justify-content: center;
    padding: 0 32rpx;
    /* #ifdef H5 */
    padding-bottom: 30rpx;
    /* #endif */
    position: fixed;
    left: 0;
    width: 100%;
    box-sizing: border-box;
    bottom: 0;
    .joinShopCartBut {
      width: 343upx;
      height: 80upx;
      border-radius: 40upx 0 0 40upx;
      background-color: #ffc300;
      color: #fffefe;
      font-size: 28upx;
      line-height: 80upx;
      text-align: center;
      margin-left: 30upx;
    }

    .buyNowBut {
      width: 90%;
      height: 90upx;
      background: linear-gradient(90deg, #ff9000, #ff5000);
      font-size: 28upx;
      line-height: 90upx;
      border-radius: 90upx;
      text-align: center;
      color: #fff;
    }

    .btn {
      width: 690rpx;
      margin: auto;
      text-align: center;
      height: 78rpx;
      line-height: 78rpx;
      border-radius: 78rpx;
      color: #fff;
      font-size: 28rpx;
      background: linear-gradient(90deg, #ff9000, #ff5000);
    }
  }
}

.skuSelectBtn {
  /* #ifdef H5 */
  padding-bottom: 30rpx;
  /* #endif */
  position: fixed;
  left: 0;
  bottom: 0;
  width: 100%;
  .selectBtn {
    text-align: center;
    width: 339rpx;
    height: 72rpx;
    background: #ff9000;
    border-radius: 8rpx 8rpx 8rpx 8rpx;
    color: #fff;
    font-family: Roboto, Roboto;
    font-weight: 400;
    font-size: 28rpx;
    line-height: 72rpx;
    border-radius: 8rpx 8rpx 8rpx 8rpx;
  }
  .selectBuyNow {
    background: #ff5000;
  }
}

.undercarriage {
  .offShelf {
    width: 700rpx;
    background: #b7b7b7;
    border-radius: 50rpx;
    height: 100rpx;
    line-height: 100rpx;
    justify-content: center;
    color: #333333;
    margin: 0 auto;
  }
}

.couponItemimg {
  width: 150upx;
  height: 60upx;
}

.joinbuyBut {
  width: 190upx;
  height: 80upx;
  background: #ff5000;
  color: #ffebc4;
  font-size: 28upx;
  line-height: 80upx;
  text-align: center;
  margin-left: 30upx;
}
</style>
